package com.sgu6.sgu6_machine.service;

import android.annotation.SuppressLint;
import android.app.IntentService;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.util.Log;

import androidx.core.app.NotificationCompat;
import androidx.core.content.FileProvider;

import com.sgu6.sgu6_machine.R;
import com.sgu6.sgu6_machine.event.ProgressEvent;
import com.sgu6.sgu6_machine.util.DownloadUtil;

import org.greenrobot.eventbus.EventBus;

import java.io.File;

public class UpdateAppS extends IntentService {

    protected static final String TAG = UpdateAppS.class.getSimpleName();

    private NotificationManager mNotificationManager;
    private Notification mNotification;

    private String apkName;
    private String savePath = "/sgu6/download/";

    NotificationCompat.Builder mBuilder;

    /**
     * Creates an IntentService.  Invoked by your subclass's constructor.
     */
    public UpdateAppS() {
        super("UpdateAppService");
    }


    @Override
    public void onCreate() {
        super.onCreate();
        mNotificationManager = (NotificationManager) getSystemService(Service.NOTIFICATION_SERVICE);
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        //APK的下载路径
        if (intent != null) {
            String apkUrl = intent.getStringExtra("downloadUrl");
            String[] args = apkUrl.split("/");
            apkName = args[args.length - 1];
            DownloadUtil.getInstance().download(apkUrl, savePath, new DownloadUtil.OnDownloadListener() {
                @Override
                public void onDownloadSuccess() {
                    EventBus.getDefault().post(new ProgressEvent(true, 100));
//                    mBuilder.setContentIntent(getInstallIntent());
//                    mNotification = mBuilder.build();
//                    mNotificationManager.notify(0, mNotification);
                    openApk1();
                }

                @Override
                public void onDownloading(int progress) {
                    notifyMsg("温馨提醒", "拾谷鸟应用更新", progress);
                    EventBus.getDefault().post(new ProgressEvent(true, progress));
                }

                @Override
                public void onDownloadFailed() {
                    EventBus.getDefault().post(new ProgressEvent(false, 0));
                }
            });
        }
    }


    private void notifyMsg(String title, String content, int progress) {
        mBuilder = new NotificationCompat.Builder(this);//为了向下兼容，这里采用了v7包下的NotificationCompat来构造
        mBuilder.setSmallIcon(R.mipmap.ic_launcher_round).setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher)).setContentTitle(title);
        if (progress > 0 && progress < 100) {
            //下载进行中
            mBuilder.setProgress(100, progress, false);
        } else {
            mBuilder.setProgress(0, 0, false);
        }
        mBuilder.setAutoCancel(true);
        mBuilder.setWhen(System.currentTimeMillis());
        mBuilder.setContentText(content);

        mNotification = mBuilder.build();
        mNotificationManager.notify(0, mNotification);
        Log.i(TAG, "notifyMsg: " + progress);
    }

    /**
     * 安装apk文件
     *
     * @return
     */
    private PendingIntent getInstallIntent() {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        Uri uri = Uri.fromFile(new File(Environment.getExternalStorageDirectory(), savePath));
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setDataAndType(uri, "application/vnd.android.package-archive");
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        return pendingIntent;
    }

    @SuppressLint("IntentReset")
    public void openApk() {
        String filePath = Environment.getExternalStorageDirectory() + savePath + apkName;


        Intent intents = new Intent();
        intents.setAction("android.intent.action.VIEW");

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intents.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            Uri contentUri = FileProvider.getUriForFile(this, "com.sgu6.sgu6_machine.provider", new File(filePath));
            intents.setDataAndType(contentUri, "application/vnd.android.package-archive");
        } else {
            Uri uri = Uri.fromFile(new File(filePath));
            intents.setDataAndType(uri, "application/vnd.android.package-archive");
            intents.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }

        startActivity(intents);
        android.os.Process.killProcess(android.os.Process.myPid());
    }

    @SuppressLint("IntentReset")
    public void openApk1() {
        String filePath = Environment.getExternalStorageDirectory() + savePath + apkName;
        File apkFile = new File(filePath);
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            Uri uri = FileProvider.getUriForFile(getApplicationContext(), getApplicationContext().getPackageName() + ".fileprovider", apkFile);
            intent.setDataAndType(uri, "application/vnd.android.package-archive");
        } else {
            intent.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");
        }
//        Uri uri = Uri.fromFile(new File(filePath));
//        intent.setDataAndType(uri, "application/vnd.android.package-archive");
        intent.putExtra("IMPLUS_INSTALL","SILENT_INSTALL");
        startActivity(intent);
        android.os.Process.killProcess(android.os.Process.myPid());
    }
}
